package service;

import model.Account;
import util.DBUtil;
import util.PasswordUtil; // 导入 PasswordUtil 类

import java.sql.*;

public class AccountService {
    private Account currentAccount = null;

    public boolean login(String accNo, String password) {
        // 对用户输入的密码进行加密
        String encryptedPassword = PasswordUtil.encrypt(password);
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM ly_accounts WHERE account_number=? AND password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, accNo);
            ps.setString(2, encryptedPassword); // 使用加密后的密码查询
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                // 传入加密后的密码
                currentAccount = new Account(accNo, encryptedPassword, rs.getDouble("balance"));
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void logout() {
        currentAccount = null;
    }

    public boolean changePassword(String oldPass, String newPass) {
        // 对旧密码进行加密比对
        if (currentAccount == null || !PasswordUtil.matches(oldPass, currentAccount.getPassword())) return false;
        // 对新密码进行加密
        String encryptedNewPass = PasswordUtil.encrypt(newPass);
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "UPDATE ly_accounts SET password=? WHERE account_number=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, encryptedNewPass); // 使用加密后的新密码更新
            ps.setString(2, currentAccount.getAccountNumber());
            if (ps.executeUpdate() > 0) {
                currentAccount.setPassword(encryptedNewPass); // 更新内存中的密码为加密后的密码
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public Account getCurrentAccount() {
        return currentAccount;
    }
}